package com.ruoyi.web.controller.business;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.business.domain.TIsvInfo;
import com.ruoyi.business.domain.TPayChannel;
import com.ruoyi.business.domain.TRecipientInfo;
import com.ruoyi.business.domain.TSmjMachineList;
import com.ruoyi.business.service.ITIsvInfoService;
import com.ruoyi.business.service.ITPayChannelService;
import com.ruoyi.business.service.ITRecipientInfoService;
import com.ruoyi.business.service.ITSmjMachineListService;
import com.ruoyi.business.service.impl.ChargeServiceImpl;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.*;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.common.utils.payment.dongwopay.DongWoPayUtils;
import com.ruoyi.common.utils.payment.pbqzpay.PubuPayUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.service.ISysConfigService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.util.Base64;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * 收款账号Controller
 * 
 * @author ruoyi
 * @date 2024-02-26
 */
@Controller
@RequestMapping("/business/recipientInfo")
public class TRecipientInfoController extends BaseController
{
    private String prefix = "business/recipientInfo";
    private final Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private ITRecipientInfoService tRecipientInfoService;

    @Autowired
    private ITIsvInfoService itIsvInfoService;

    @Autowired
    private ISysConfigService iSysConfigService;

    @Autowired
    private ITSmjMachineListService itSmjMachineListService;

    @Autowired
    private ITPayChannelService payChannelService;
    @Autowired
    private ChargeServiceImpl chargeServiceImpl;


    @RequiresPermissions("business:recipientInfo:view")
    @GetMapping()
    public String recipientInfo(ModelMap mmap)
    {
        mmap.put("tIsvInfo", new TIsvInfo());
        return prefix + "/recipientInfo";
    }

    /**
     * 查询收款账号列表
     */
    @RequiresPermissions("business:recipientInfo:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(TRecipientInfo tRecipientInfo)
    {
        startPage();
        List<TRecipientInfo> list = tRecipientInfoService.selectTRecipientInfoList(tRecipientInfo);
        return getDataTable(list);
    }

    /**
     * 导出收款账号列表
     */
    @RequiresPermissions("business:recipientInfo:export")
    @Log(title = "收款账号", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(TRecipientInfo tRecipientInfo)
    {
        List<TRecipientInfo> list = tRecipientInfoService.selectTRecipientInfoList(tRecipientInfo);
        ExcelUtil<TRecipientInfo> util = new ExcelUtil<TRecipientInfo>(TRecipientInfo.class);
        return util.exportExcel(list, "收款账号数据");
    }

    /**
     * 新增收款账号
     */
    @GetMapping("/add")
    public String add(ModelMap mmap)
    {
        mmap.put("tIsvInfo", new TIsvInfo());
        mmap.put("fileid", RandomUtil.randomString(10));
        return prefix + "/add";
    }

    @GetMapping("/addChildAccount/{id}")
    public String addChildAccount(@PathVariable("id") Long id, ModelMap mmap)
    {
        TPayChannel tPayChannel = payChannelService.selectTPayChannelById(id);
        mmap.put("tPayChannel", tPayChannel);
        mmap.put("tIsvInfo", new TIsvInfo());
        mmap.put("fileid", RandomUtil.randomString(10));

        return prefix + "/recipientInfoChild";
    }

    /**
     * 新增保存收款账号
     */
    @RequiresPermissions("business:recipientInfo:add")
    @Log(title = "收款账号", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(TRecipientInfo tRecipientInfo)
    {
        tRecipientInfo.setCreateTime(DateUtils.getNowDate());
        TPayChannel payChannelParam = new TPayChannel();
        payChannelParam.setChannel(tRecipientInfo.getChannel());
        TPayChannel orderChannel = payChannelService.selectTPayChannelList(payChannelParam).get(0);
        tRecipientInfo.setNeedOnline(orderChannel.getNeedOnLine());
        tRecipientInfo.setLoginType(orderChannel.getLoginType());
        if(ObjectUtil.isNotEmpty(tRecipientInfo.getPassWord())){
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("password",tRecipientInfo.getPassWord());
            tRecipientInfo.setAccountJson(jsonObject.toJSONString());
        }
        if(ObjectUtil.isNotEmpty(tRecipientInfo.getYlKey())){
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("ylKey",tRecipientInfo.getYlKey());
            tRecipientInfo.setAccountJson(jsonObject.toJSONString());
        }
        if(ObjectUtil.isEmpty(tRecipientInfo.getShopNickname())){
            tRecipientInfo.setShopNickname(null);
        }
        if(ObjectUtil.isEmpty(tRecipientInfo.getRealName())){
            tRecipientInfo.setRealName(tRecipientInfo.getChannelAccount());
        }
        if(ObjectUtil.isEmpty(tRecipientInfo.getShopClerkAccount())){
            tRecipientInfo.setShopClerkAccount(null);
        }
        if(tRecipientInfo.getChannel().equals("card_to_card")){
            if(tRecipientInfo.getBankName().contains("邮储")){
                tRecipientInfo.setWeiShu(tRecipientInfo.getCardNo().substring(tRecipientInfo.getCardNo().length()-3, tRecipientInfo.getCardNo().length()));
            }else{
                tRecipientInfo.setWeiShu(tRecipientInfo.getCardNo().substring(tRecipientInfo.getCardNo().length()-4, tRecipientInfo.getCardNo().length()));
            }
        }
        if(tRecipientInfo.getChannel().startsWith("isv_alipay")){
            tRecipientInfo.setAlipayCardid(tRecipientInfo.getIsvId());
        }
        JSONObject jsonObject = new JSONObject();
        if(tRecipientInfo.getChannel().startsWith("gf_alipay")){

            jsonObject.put("aliPublicKey",tRecipientInfo.getAliPublicKey());
            jsonObject.put("aliPrivateKey",tRecipientInfo.getAliPrivateKey());
            tRecipientInfo.setAccountJson(jsonObject.toJSONString());
        }
        if(tRecipientInfo.getChannel().startsWith("gf_cert_alipay")){

            jsonObject.put("certAliPrivateKey",tRecipientInfo.getCertAliPrivateKey());
            jsonObject.put("certAliRootPath",tRecipientInfo.getCertAliRootPath());
            jsonObject.put("certAliPublicPath",tRecipientInfo.getCertAliPublicPath());
            jsonObject.put("certAppPublicPath",tRecipientInfo.getCertAppPublicPath());
            tRecipientInfo.setAccountJson(jsonObject.toJSONString());
        }
        if(tRecipientInfo.getChannel().startsWith("lakala_pay")){

            jsonObject.put("lklShopname",tRecipientInfo.getLklShopname());
            jsonObject.put("lklShopno",tRecipientInfo.getLklShopno());
            jsonObject.put("lklTermno",tRecipientInfo.getLklTermno());
            tRecipientInfo.setAccountJson(jsonObject.toJSONString());
        }
        //拉卡拉缴费易
        if(tRecipientInfo.getChannel().startsWith("lakala_jfy_pay")){
            jsonObject.put("lklShopname",tRecipientInfo.getLklShopname());
            jsonObject.put("lklShopno",tRecipientInfo.getLklShopno());
            jsonObject.put("lklTermno",tRecipientInfo.getLklTermno());
            tRecipientInfo.setAccountJson(jsonObject.toJSONString());
        }

        if(tRecipientInfo.getChannel().startsWith("game_pay")){

            jsonObject.put("key",tRecipientInfo.getGameKey());
            jsonObject.put("reqUrl",tRecipientInfo.getGameUrl());
            jsonObject.put("payType",tRecipientInfo.getGamepayType());
            jsonObject.put("pid",tRecipientInfo.getGamePid());
            jsonObject.put("method",tRecipientInfo.getGamepayMethod());
            tRecipientInfo.setAccountJson(jsonObject.toJSONString());
        }

        if(tRecipientInfo.getChannel().startsWith("yunyinqian_pay")){

            jsonObject.put("ck",tRecipientInfo.getYyqCk());
            jsonObject.put("userId",tRecipientInfo.getYyqUserId());
            jsonObject.put("orderSubject",tRecipientInfo.getYyqOrderSubject());
            tRecipientInfo.setAccountJson(jsonObject.toJSONString());
        }
        if(orderChannel.getNeedOnLine()==1 ){

            if(orderChannel.getLoginType().equals("passwdcode") || orderChannel.getLoginType().equals("passwd")){
                jsonObject.put("loginUrl",tRecipientInfo.getLoginUrl());
                jsonObject.put("password",tRecipientInfo.getPassWord());
            }else if(orderChannel.getLoginType().equals("ck")){
                jsonObject.put("ck",tRecipientInfo.getLoginCk());
            }
            tRecipientInfo.setAccountJson(jsonObject.toJSONString());
        }
        if(tRecipientInfo.getUserId()==null)
            tRecipientInfo.setUserId(ShiroUtils.getUserId());
        if(tRecipientInfo.getLimitDayMoney()!=null)
            tRecipientInfo.setLimitDayMoney(tRecipientInfo.getLimitDayMoney()*100);
        if(tRecipientInfo.getLimitMaxMoney()!=null)
            tRecipientInfo.setLimitMaxMoney(tRecipientInfo.getLimitMaxMoney()*100);
        if(tRecipientInfo.getOnecePayLimit()!=null)
            tRecipientInfo.setOnecePayLimit(tRecipientInfo.getOnecePayLimit()*100);
        return toAjax(tRecipientInfoService.insertTRecipientInfo(tRecipientInfo));
    }

    /**
     * 修改收款账号
     */
    @RequiresPermissions("business:recipientInfo:edit")
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap)
    {
        TRecipientInfo tRecipientInfo = tRecipientInfoService.selectTRecipientInfoById(id);
        tRecipientInfo.setCityVal(tRecipientInfo.getCity());
        tRecipientInfo.setChannelVal(tRecipientInfo.getChannel());
        String accountJson = tRecipientInfo.getAccountJson();
        if(StringUtils.isNotBlank(accountJson)){
            JSONObject  accountObj = JSONObject.parseObject(accountJson);
            tRecipientInfo.setLoginCk(accountObj.getString("ck"));
            tRecipientInfo.setLoginUrl(accountObj.getString("loginUrl"));
            tRecipientInfo.setPassWord(accountObj.getString("password"));
            if(tRecipientInfo.getChannel().startsWith("lakala_pay")){
                tRecipientInfo.setLklShopname(accountObj.getString("lklShopname"));
                tRecipientInfo.setLklShopno(accountObj.getString("lklShopno"));
                tRecipientInfo.setLklTermno(accountObj.getString("lklTermno"));
            }
            if(tRecipientInfo.getChannel().startsWith("gf_alipay")){
                tRecipientInfo.setAliPublicKey(accountObj.getString("aliPublicKey"));
                tRecipientInfo.setAliPrivateKey(accountObj.getString("aliPrivateKey"));
            }
            if(tRecipientInfo.getChannel().startsWith("game_pay")){
                tRecipientInfo.setGameKey(accountObj.getString("key"));
                tRecipientInfo.setGamePid(accountObj.getString("pid"));
                tRecipientInfo.setGameUrl(accountObj.getString("reqUrl"));
                tRecipientInfo.setGamepayType(accountObj.getString("payType"));
                tRecipientInfo.setGamepayMethod(accountObj.getString("method"));
            }
            if(tRecipientInfo.getChannel().startsWith("yunyinqian_pay")){
                tRecipientInfo.setYyqCk(accountObj.getString("ck"));
                tRecipientInfo.setYyqUserId(accountObj.getString("userId"));
                tRecipientInfo.setYyqOrderSubject(accountObj.getString("orderSubject"));
            }
            if(tRecipientInfo.getChannel().startsWith("lakala_jfy_pay")){
                tRecipientInfo.setLklShopname(accountObj.getString("lklShopname"));
                tRecipientInfo.setLklShopno(accountObj.getString("lklShopno"));
                tRecipientInfo.setLklTermno(accountObj.getString("lklTermno"));
            }
        }

        mmap.put("tRecipientInfo", tRecipientInfo);
        return prefix + "/edit";
    }

    @RequiresPermissions("business:recipientInfo:edit")
    @GetMapping("/copy/{id}")
    public String copy(@PathVariable("id") Long id, ModelMap mmap)
    {
        TRecipientInfo tRecipientInfo = tRecipientInfoService.selectTRecipientInfoById(id);
        tRecipientInfo.setCityVal(tRecipientInfo.getCity());
        tRecipientInfo.setChannelVal(tRecipientInfo.getChannel());
        String accountJson = tRecipientInfo.getAccountJson();
        JSONObject  accountObj = JSONObject.parseObject(accountJson);
        tRecipientInfo.setLoginCk(accountObj.getString("ck"));
        tRecipientInfo.setLoginUrl(accountObj.getString("loginUrl"));
        tRecipientInfo.setPassWord(accountObj.getString("password"));
        if(tRecipientInfo.getChannel().startsWith("lakala_pay")){
            tRecipientInfo.setLklShopname(accountObj.getString("lklShopname"));
            tRecipientInfo.setLklShopno(accountObj.getString("lklShopno"));
            tRecipientInfo.setLklTermno(accountObj.getString("lklTermno"));
        }
        if(tRecipientInfo.getChannel().startsWith("gf_alipay")){
            tRecipientInfo.setAliPublicKey(accountObj.getString("aliPublicKey"));
            tRecipientInfo.setAliPrivateKey(accountObj.getString("aliPrivateKey"));
        }
        if(tRecipientInfo.getChannel().startsWith("game_pay")){
            tRecipientInfo.setGameKey(accountObj.getString("key"));
            tRecipientInfo.setGamePid(accountObj.getString("pid"));
            tRecipientInfo.setGameUrl(accountObj.getString("reqUrl"));
            tRecipientInfo.setGamepayType(accountObj.getString("payType"));
            tRecipientInfo.setGamepayMethod(accountObj.getString("method"));
        }

        mmap.put("tRecipientInfo", tRecipientInfo);
        return prefix + "/copy";
    }


    /**
     * 修改保存收款账号
     */
    @RequiresPermissions("business:recipientInfo:edit")
    @Log(title = "收款账号", businessType = BusinessType.UPDATE)
    @PostMapping("/copy")
    @ResponseBody
    public AjaxResult copySave(TRecipientInfo tRecipientInfo)
    {
        tRecipientInfo.setChannel(tRecipientInfo.getChannelVal());
        TRecipientInfo oldtRecipientInfo = tRecipientInfoService.selectTRecipientInfoById(tRecipientInfo.getId());
        TRecipientInfo newTRecipientInfo = new TRecipientInfo();
        BeanUtils.copyBeanProp(newTRecipientInfo,oldtRecipientInfo);
        newTRecipientInfo.setCreateTime(DateUtils.getNowDate());
        newTRecipientInfo.setId(null);
        newTRecipientInfo.setChannel(tRecipientInfo.getChannelVal());

        if(ObjectUtil.isNotEmpty(tRecipientInfo.getPassWord())){
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("password",tRecipientInfo.getPassWord());
            newTRecipientInfo.setAccountJson(jsonObject.toJSONString());
        }
        TPayChannel payChannelParam = new TPayChannel();
        payChannelParam.setChannel(tRecipientInfo.getChannel());
        TPayChannel orderChannel = payChannelService.selectTPayChannelList(payChannelParam).get(0);
        if(tRecipientInfo.getChannel().equals("card_to_card")){
            if(tRecipientInfo.getBankName().contains("邮储")){
                newTRecipientInfo.setWeiShu(tRecipientInfo.getCardNo().substring(tRecipientInfo.getCardNo().length()-3, tRecipientInfo.getCardNo().length()));
            }else{
                newTRecipientInfo.setWeiShu(tRecipientInfo.getCardNo().substring(tRecipientInfo.getCardNo().length()-4, tRecipientInfo.getCardNo().length()));
            }
        }
        if(tRecipientInfo.getChannel().startsWith("isv_alipay")){
            newTRecipientInfo.setAlipayCardid(tRecipientInfo.getIsvId());
        }
        JSONObject jsonObject = new JSONObject();
        if(tRecipientInfo.getChannel().startsWith("gf_alipay")){

            jsonObject.put("aliPublicKey",tRecipientInfo.getAliPublicKey());
            jsonObject.put("aliPrivateKey",tRecipientInfo.getAliPrivateKey());
            newTRecipientInfo.setAccountJson(jsonObject.toJSONString());
        }
        if(tRecipientInfo.getChannel().startsWith("gf_cert_alipay")){

            jsonObject.put("certAliPrivateKey",tRecipientInfo.getCertAliPrivateKey());
            jsonObject.put("certAliRootPath",tRecipientInfo.getCertAliRootPath());
            jsonObject.put("certAliPublicPath",tRecipientInfo.getCertAliPublicPath());
            jsonObject.put("certAppPublicPath",tRecipientInfo.getCertAppPublicPath());
            newTRecipientInfo.setAccountJson(jsonObject.toJSONString());
        }
        if(tRecipientInfo.getChannel().startsWith("lakala_pay")){

            jsonObject.put("lklShopname",tRecipientInfo.getLklShopname());
            jsonObject.put("lklShopno",tRecipientInfo.getLklShopno());
            jsonObject.put("lklTermno",tRecipientInfo.getLklTermno());
            newTRecipientInfo.setAccountJson(jsonObject.toJSONString());
        }

        if(tRecipientInfo.getChannel().startsWith("game_pay")){

            jsonObject.put("key",tRecipientInfo.getGameKey());
            jsonObject.put("reqUrl",tRecipientInfo.getGameUrl());
            jsonObject.put("payType",tRecipientInfo.getGamepayType());
            jsonObject.put("pid",tRecipientInfo.getGamePid());
            jsonObject.put("method",tRecipientInfo.getGamepayMethod());
            newTRecipientInfo.setAccountJson(jsonObject.toJSONString());
        }
        if(tRecipientInfo.getChannel().startsWith("yunyinqian_pay")){

            jsonObject.put("ck",tRecipientInfo.getYyqCk());
            jsonObject.put("userId",tRecipientInfo.getYyqUserId());
            jsonObject.put("orderSubject",tRecipientInfo.getYyqOrderSubject());
            tRecipientInfo.setAccountJson(jsonObject.toJSONString());
        }
        if(orderChannel.getNeedOnLine()==1 ){

            if(orderChannel.getLoginType().equals("passwdcode") || orderChannel.getLoginType().equals("passwd")){
                jsonObject.put("loginUrl",tRecipientInfo.getLoginUrl());
                jsonObject.put("password",tRecipientInfo.getPassWord());
            }else if(orderChannel.getLoginType().equals("ck")){
                jsonObject.put("ck",tRecipientInfo.getLoginCk());
            }
            newTRecipientInfo.setAccountJson(jsonObject.toJSONString());
        }
        newTRecipientInfo.setChannelAccount(tRecipientInfo.getChannelAccount());
        newTRecipientInfo.setRealName(tRecipientInfo.getRealName());
        if(tRecipientInfo.getLimitDayMoney()!=null)
            newTRecipientInfo.setLimitDayMoney(tRecipientInfo.getLimitDayMoney()*100);
        if(tRecipientInfo.getLimitMaxMoney()!=null)
            newTRecipientInfo.setLimitMaxMoney(tRecipientInfo.getLimitMaxMoney()*100);
        if(tRecipientInfo.getOnecePayLimit()!=null)
            newTRecipientInfo.setOnecePayLimit(tRecipientInfo.getOnecePayLimit()*100);
        newTRecipientInfo.setLimitDayCount(tRecipientInfo.getLimitDayCount());
        newTRecipientInfo.setLimitMaxCount(tRecipientInfo.getLimitMaxCount());
        return toAjax(tRecipientInfoService.insertTRecipientInfo(newTRecipientInfo));
    }

    /**
     * 修改保存收款账号
     */
    @RequiresPermissions("business:recipientInfo:edit")
    @Log(title = "收款账号", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(TRecipientInfo tRecipientInfo)
    {
        tRecipientInfo.setChannel(tRecipientInfo.getChannelVal());
        tRecipientInfo.setUpdateTime(DateUtils.getNowDate());
        if(ObjectUtil.isNotEmpty(tRecipientInfo.getPassWord())){
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("password",tRecipientInfo.getPassWord());
            tRecipientInfo.setAccountJson(jsonObject.toJSONString());
        }
        TPayChannel payChannelParam = new TPayChannel();
        payChannelParam.setChannel(tRecipientInfo.getChannel());
        TPayChannel orderChannel = payChannelService.selectTPayChannelList(payChannelParam).get(0);
        if(tRecipientInfo.getChannel().equals("card_to_card")){
            if(tRecipientInfo.getBankName().contains("邮储")){
                tRecipientInfo.setWeiShu(tRecipientInfo.getCardNo().substring(tRecipientInfo.getCardNo().length()-3, tRecipientInfo.getCardNo().length()));
            }else{
                tRecipientInfo.setWeiShu(tRecipientInfo.getCardNo().substring(tRecipientInfo.getCardNo().length()-4, tRecipientInfo.getCardNo().length()));
            }
        }
        if(tRecipientInfo.getChannel().startsWith("isv_alipay")){
            tRecipientInfo.setAlipayCardid(tRecipientInfo.getIsvId());
        }
        JSONObject jsonObject = new JSONObject();
        if(tRecipientInfo.getChannel().startsWith("gf_alipay")){

            jsonObject.put("aliPublicKey",tRecipientInfo.getAliPublicKey());
            jsonObject.put("aliPrivateKey",tRecipientInfo.getAliPrivateKey());
            tRecipientInfo.setAccountJson(jsonObject.toJSONString());
        }
        if(tRecipientInfo.getChannel().startsWith("gf_cert_alipay")){

            jsonObject.put("certAliPrivateKey",tRecipientInfo.getCertAliPrivateKey());
            jsonObject.put("certAliRootPath",tRecipientInfo.getCertAliRootPath());
            jsonObject.put("certAliPublicPath",tRecipientInfo.getCertAliPublicPath());
            jsonObject.put("certAppPublicPath",tRecipientInfo.getCertAppPublicPath());
            tRecipientInfo.setAccountJson(jsonObject.toJSONString());
        }
        if(tRecipientInfo.getChannel().startsWith("lakala_pay")){

            jsonObject.put("lklShopname",tRecipientInfo.getLklShopname());
            jsonObject.put("lklShopno",tRecipientInfo.getLklShopno());
            jsonObject.put("lklTermno",tRecipientInfo.getLklTermno());
            tRecipientInfo.setAccountJson(jsonObject.toJSONString());
        }

        if(tRecipientInfo.getChannel().startsWith("game_pay")){

            jsonObject.put("key",tRecipientInfo.getGameKey());
            jsonObject.put("reqUrl",tRecipientInfo.getGameUrl());
            jsonObject.put("payType",tRecipientInfo.getGamepayType());
            jsonObject.put("pid",tRecipientInfo.getGamePid());
            jsonObject.put("method",tRecipientInfo.getGamepayMethod());
            tRecipientInfo.setAccountJson(jsonObject.toJSONString());
        }
        if(tRecipientInfo.getChannel().startsWith("yunyinqian_pay")){

            jsonObject.put("ck",tRecipientInfo.getYyqCk());
            jsonObject.put("userId",tRecipientInfo.getYyqUserId());
            jsonObject.put("orderSubject",tRecipientInfo.getYyqOrderSubject());
            tRecipientInfo.setAccountJson(jsonObject.toJSONString());
        }
        if(orderChannel.getNeedOnLine()==1 ){

            if(orderChannel.getLoginType().equals("passwdcode") || orderChannel.getLoginType().equals("passwd")){
                jsonObject.put("loginUrl",tRecipientInfo.getLoginUrl());
                jsonObject.put("password",tRecipientInfo.getPassWord());
            }else if(orderChannel.getLoginType().equals("ck")){
                jsonObject.put("ck",tRecipientInfo.getLoginCk());
            }
            tRecipientInfo.setAccountJson(jsonObject.toJSONString());
        }
        if(tRecipientInfo.getLimitDayMoney()!=null)
            tRecipientInfo.setLimitDayMoney(tRecipientInfo.getLimitDayMoney()*100);
        if(tRecipientInfo.getLimitMaxMoney()!=null)
            tRecipientInfo.setLimitMaxMoney(tRecipientInfo.getLimitMaxMoney()*100);
        if(tRecipientInfo.getOnecePayLimit()!=null)
            tRecipientInfo.setOnecePayLimit(tRecipientInfo.getOnecePayLimit()*100);
        return toAjax(tRecipientInfoService.updateTRecipientInfo(tRecipientInfo));
    }

    /**
     * 删除收款账号
     */
    @RequiresPermissions("business:recipientInfo:remove")
    @Log(title = "收款账号", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(tRecipientInfoService.deleteTRecipientInfoByIds(ids));
    }

    @RequiresPermissions("business:recipientInfo:add")
    @GetMapping("/isvAuth/{id}")
    public String isvAuth(@PathVariable("id") Long id, ModelMap mmap)
    {
        TRecipientInfo tRecipientInfo = tRecipientInfoService.selectTRecipientInfoById(id);
        TIsvInfo query = new TIsvInfo();
        query.setStatus(0);
        List<TIsvInfo> isvInfoList = itIsvInfoService.selectTIsvInfoList(query);
        if(isvInfoList.size()==0){
            throw new RuntimeException("未查询到有效的服务商信息！");
        }
        TIsvInfo isvInfo = isvInfoList.get(0);
        String domain = iSysConfigService.selectConfigByKey("domain");
        String accountJson = tRecipientInfo.getAccountJson();
        JSONObject accountObj = JSONObject.parseObject(accountJson);
        accountObj.put("isvName",isvInfo.getIsvName());
        tRecipientInfo.setAccountJson(JSONObject.toJSONString(accountObj));
        tRecipientInfoService.updateTRecipientInfo(tRecipientInfo);
        String authUrl = "https://openauth.alipay.com/oauth2/appToAppAuth.htm?app_id="+isvInfo.getIsvAppId()+"&redirect_uri="+domain+"api/v1/isvAuth/"+tRecipientInfo.getId();
        mmap.put("authUrl", authUrl);
        mmap.put("tRecipientInfo", tRecipientInfo);
        return prefix + "/isvAuth";
    }



    @GetMapping("/smsLogin/{id}")
    public String smsLogin(@PathVariable("id") Long id, ModelMap mmap)
    {
        TRecipientInfo tRecipientInfo = tRecipientInfoService.selectTRecipientInfoById(id);
        mmap.put("tRecipientInfo", tRecipientInfo);
        return prefix + "/smsLogin";
    }

    @Log(title = "用户收款号状态变更", businessType = BusinessType.UPDATE)
    @RequiresPermissions("business:recipientInfo:edit")
    @PostMapping("/changeStatus")
    @ResponseBody
    public AjaxResult changeStatus(TRecipientInfo tUserRecipientInfo) {
        TRecipientInfo newtUserRecipientInfo = tRecipientInfoService.selectTRecipientInfoById(tUserRecipientInfo.getId());
        newtUserRecipientInfo.setAvailable(tUserRecipientInfo.getAvailable());
        return toAjax(tRecipientInfoService.updateTRecipientInfo(newtUserRecipientInfo));
//        return toAjax(tNginxInfoService.updateTNginxInfo(tNginxInfo));
    }

    @PostMapping("/login/{id}")
    @ResponseBody
    public AjaxResult login(@PathVariable("id") Long id)
    {
        TRecipientInfo tRecipientInfo = tRecipientInfoService.selectTRecipientInfoById(id);
        long userId = ShiroUtils.getUserId();
        HashMap<String, String> headerMap = new HashMap();
        if(tRecipientInfo.getChannel().equalsIgnoreCase("ZHIYUAN_GM_PAY_ALI_H5")){
            JSONObject  jsonObject = JSONObject.parseObject(tRecipientInfo.getAccountJson());
            String key = jsonObject.getString("key");
            String token = jsonObject.getString("token");
            String loginUrl = "https://zy.live/home/isLogin";
            String param ="key="+key+"&_token="+token;

            headerMap.put("authority","www.zy.live");
            headerMap.put("accept","application/json, text/javascript, */*; q=0.01");
            headerMap.put("accept-language","zh-CN,zh;q=0.9");
            headerMap.put("cache-control","no-cache");
            headerMap.put("content-type","application/x-www-form-urlencoded; charset=UTF-8");
            headerMap.put("origin","https://www.zy.live");
            headerMap.put("pragma","no-cache");
            headerMap.put("referer","https://www.zy.live/home/login/index");
            headerMap.put("sec-ch-ua","\"Chromium\";v=\"110\", \"Not A(Brand\";v=\"24\", \"Google Chrome\";v=\"110\"");
            headerMap.put("sec-ch-ua-mobile","?0");
            headerMap.put("sec-ch-ua-platform","\"Windows\"");
            headerMap.put("sec-fetch-dest","empty");
            headerMap.put("sec-fetch-mode","cors");
            headerMap.put("sec-fetch-site","same-origin");
            headerMap.put("user-agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36");
            headerMap.put("x-requested-with","XMLHttpRequest");
            headerMap.put("cookie",jsonObject.getString("loginCookies"));
            String loginRes = "";// HttpUtils.sendPostRequest(loginUrl,headerMap,param);
            JSONObject loginResObj = JSONObject.parseObject(loginRes);
            if(loginResObj.getIntValue("code")!=0){
                return error("未登录");
            }
            tRecipientInfo.setAvailable(1);
            tRecipientInfo.setOnline(1);
            tRecipientInfo.setAccountJson(jsonObject.toJSONString());
            tRecipientInfoService.updateTRecipientInfo(tRecipientInfo);
            return success("登录成功");
        } else if (tRecipientInfo.getChannel().contains("_smj_sm_h5")) {
            String accountJson = tRecipientInfo.getAccountJson();
            JSONObject  accountObj = JSONObject.parseObject(accountJson);

            headerMap.put("User-Agent","Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36");
            logger.info("后台登录HTMLurl："+accountObj.getString("loginUrl"));
            HttpResponse httpResponse = HttpUtils.httpFormGet(accountObj.getString("loginUrl"),headerMap,"","售货机【盛马】","");
            String cookies = httpResponse.getCookie();
            headerMap.put("Cookie",cookies);
            logger.info("登录cookies：{}",cookies);
            accountObj.put("cookie",cookies);
            accountObj.put("User-Agent","Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36");
            HashMap<String, String> requestMap = new HashMap();
            requestMap.put("username",tRecipientInfo.getChannelAccount());
            requestMap.put("password",accountObj.getString("password"));
            String[] loginUrls = accountObj.getString("loginUrl").split("login.html");
            logger.info("登录地址：{},用户名：{},password:{}",loginUrls[0]+"user/login.action",tRecipientInfo.getChannelAccount(),accountObj.getString("password"));
            HttpResponse b =  HttpUtils.httpFormPost(loginUrls[0]+"user/login.action",headerMap,cookies,requestMap,"售货机【盛马】","");
            tRecipientInfo.setAccountJson(accountObj.toJSONString());
            tRecipientInfoService.updateTRecipientInfo(tRecipientInfo);
            //获取售货机列表
            //sbId=&sbName=&version=&sbNo=&status=-1&online=-1&roleType=10&partnerUserId=0&pageno=
//            itSmjMachineListService.deleteTSmjMachineListByUserRecipientId(tUserRecipientInfo.getId());
            requestMap = new HashMap();
            requestMap.put("status","-1");
            requestMap.put("roleType","10");
            HttpResponse c = HttpUtils.httpFormPost(loginUrls[0]+"operator/machine.html",headerMap,cookies,requestMap,"售货机【盛马】机器列表","");
            if(c.getBody().contains("登录")){
                return error("登录失败");
            }
            Elements lielements = c.getDocument().select("tbody");
            Elements trs = lielements.first().select("tr");
            for (int i = 0; i < trs.size(); i++) {
                TSmjMachineList query = new TSmjMachineList();
                TSmjMachineList tSmjMachineList = new TSmjMachineList();
                tSmjMachineList.setMachineType("SHENGMA");
                Element tr = trs.get(i);
                Elements cells = tr.select("td");
                query.setMachineCode(cells.get(2).select("a").first().text());
                List<TSmjMachineList> tSmjMachineLists =  itSmjMachineListService.selectTSmjMachineListList(query);
                if(tSmjMachineLists.size()>0){
                    tSmjMachineList = tSmjMachineLists.get(0);
                }
                tSmjMachineList.setUserId(tRecipientInfo.getUserId());
                logger.info("操作状态:{},网络状况:{}",cells.get(7).select("span").first().text(),cells.get(14).select("span").first().text());
                if(cells.get(7).select("span").first().text().equals("正常售卖") && cells.get(14).select("span").first().text().equals("在线")){
                    tSmjMachineList.setMachineStatus(1);
                }else {
                    tSmjMachineList.setMachineStatus(0);
                }
                Element checkboxe = cells.get(0).select("input[type=checkbox]").first();
                tSmjMachineList.setSmMachineId(checkboxe.val());
                logger.info("机器编码:{},机器名称:{}",cells.get(2).select("a").first().text(),cells.get(3).text());
//                tSmjMachineList.setMachineGoodUrl(cells.get(2).select("a").first().attr("href").replace("desc","huodao"));
                tSmjMachineList.setUserRecipientId(tRecipientInfo.getId());
                tSmjMachineList.setRealChannelCode(tRecipientInfo.getChannel());
                tSmjMachineList.setMachineCode(cells.get(2).select("a").first().text());
                tSmjMachineList.setMachineName(cells.get(3).text());
                if(tSmjMachineLists.size()>0){
                    itSmjMachineListService.updateTSmjMachineList(tSmjMachineList);
                }else {
                    itSmjMachineListService.insertTSmjMachineList(tSmjMachineList);
                }
            }
            tRecipientInfo.setOnline(1);
            tRecipientInfoService.updateTRecipientInfo(tRecipientInfo);

            return success("登录成功");
        } else if (tRecipientInfo.getChannel().contains("_smj_xlm_h5")) {
            String accountJson = tRecipientInfo.getAccountJson();
            JSONObject  accountObj = JSONObject.parseObject(accountJson);

            headerMap.put("User-Agent","Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36");
            logger.info("后台登录HTMLurl："+accountObj.getString("loginUrl"));
            HttpResponse httpResponse = HttpUtils.httpFormGet(accountObj.getString("loginUrl"),headerMap,"","售货机【小懒猫】","");
            String cookies = httpResponse.getCookie();
            headerMap.put("Cookie",cookies);
            logger.info("登录cookies：{}",cookies);
            accountObj.put("cookie",cookies);
            accountObj.put("User-Agent","Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36");
            HashMap<String, String> requestMap = new HashMap();
            requestMap.put("userCode",tRecipientInfo.getChannelAccount());
            requestMap.put("password",accountObj.getString("password"));
            logger.info("登录地址：{},用户名：{},password:{}","https://xxh.aotaki.com/api/h5b/login",tRecipientInfo.getChannelAccount(),accountObj.getString("password"));
            HttpResponse b =  HttpUtils.httpFormPost("https://xxh.aotaki.com/api/h5b/login",headerMap,cookies,requestMap,"售货机【小懒猫】","");
            cookies = cookies+";"+b.getCookie();
            accountObj.put("cookie",cookies);
            headerMap.put("Cookie",cookies);
            String userStr = b.getBody();
            JSONObject userObj = JSONObject.parseObject(userStr);
            if(!userObj.getBooleanValue("success")){
                return error("登录失败");
            }
            accountObj.put("deptId",userObj.getJSONObject("user").getString("deptId"));
            tRecipientInfo.setAccountJson(accountObj.toJSONString());
            tRecipientInfoService.updateTRecipientInfo(tRecipientInfo);
            //获取售货机列表
            requestMap = new HashMap();
            requestMap.put("supDeptId","");
            requestMap.put("vmCode","");
            requestMap.put("saleLocName","");
            requestMap.put("contain","1");
            requestMap.put("vmStatus","");
            requestMap.put("trouble","false");
            requestMap.put("pageIndex","0");
            requestMap.put("pageSize","15");
            requestMap.put("vmOrderBy","vmCode");
            HttpResponse saleLocRes =  HttpUtils.httpFormPost("https://xxh.aotaki.com/api/saleLoc/h5b/search",headerMap,cookies,requestMap,"售货机【小懒猫】","");
            JSONObject saleLocResObj = JSONObject.parseObject(saleLocRes.getBody());
            JSONArray saleLocList = saleLocResObj.getJSONObject("page").getJSONArray("rows");
            for (int i = 0; i < saleLocList.size(); i++) {
//                requestMap = new HashMap();
//                requestMap.put("supDeptId","");
//                HttpResponse saleLocDetailRes =  HttpUtils.httpFormPost("https://xxh.aotaki.com/api/saleLoc/h5b/detail",headerMap,cookies,requestMap,"售货机【小懒猫】","");
//                JSONObject saleLocDetailResObj = JSONObject.parseObject(saleLocDetailRes.getBody());
                TSmjMachineList query = new TSmjMachineList();
                TSmjMachineList tSmjMachineList = new TSmjMachineList();
                JSONObject saleLocObj = (JSONObject)saleLocList.get(i);
                query.setSmMachineId(saleLocObj.getString("saleLocId"));
                query.setMachineType("XIAOLANMAO");
                tSmjMachineList.setMachineType("XIAOLANMAO");
                List<TSmjMachineList> tSmjMachineLists =  itSmjMachineListService.selectTSmjMachineListList(query);
                if(tSmjMachineLists.size()>0){
                    tSmjMachineList = tSmjMachineLists.get(0);
                }
                tSmjMachineList.setUserId(tRecipientInfo.getUserId());
                logger.info("状态:{}",saleLocObj.getString("vmStatus"));
                if(saleLocObj.getString("vmStatus").equals("1")){
                    tSmjMachineList.setMachineStatus(1);
                }else {
                    tSmjMachineList.setMachineStatus(0);
                }

                tSmjMachineList.setSmMachineId(saleLocObj.getString("saleLocId"));
                logger.info("机器编码:{},机器名称:{}",saleLocObj.getString("saleLocId"),saleLocObj.getString("saleLocName"));
//                tSmjMachineList.setMachineGoodUrl(cells.get(2).select("a").first().attr("href").replace("desc","huodao"));
                tSmjMachineList.setUserRecipientId(tRecipientInfo.getId());
                tSmjMachineList.setRealChannelCode(tRecipientInfo.getChannel());
                tSmjMachineList.setMachineCode(saleLocObj.getString("saleLocId"));
                tSmjMachineList.setMachineName(saleLocObj.getString("saleLocName"));
                if(tSmjMachineLists.size()>0){
                    itSmjMachineListService.updateTSmjMachineList(tSmjMachineList);
                }else {
                    itSmjMachineListService.insertTSmjMachineList(tSmjMachineList);
                }
            }
            tRecipientInfo.setOnline(1);
            tRecipientInfoService.updateTRecipientInfo(tRecipientInfo);

            return success("登录成功");
        }else if (tRecipientInfo.getChannel().contains("_pbqz_h5")) {
            //瀑布圈子
            long time = System.currentTimeMillis()/1000;
            String accountJson = tRecipientInfo.getAccountJson();
            JSONObject  accountObj = JSONObject.parseObject(accountJson);

            JSONObject  loginObj  = new JSONObject();
            loginObj.put("pwd",accountObj.getString("password"));
            loginObj.put("userName",tRecipientInfo.getChannelAccount());
            String sign = PubuPayUtils.getSign(time,loginObj,"");
            String loginUrl = "http://api.openpubu.com/open/login?token=&time="+time+"&sign="+sign+"&client_channel=2&api_version=2.2.5";
            String loginRes = HttpUtils.sendJsonMessage(loginUrl,headerMap,loginObj.toJSONString());
            JSONObject  loginResObj = JSONObject.parseObject(loginRes);
            if(loginResObj.getIntValue("status")!=200){
                return error("登录失败");
            }
            JSONObject userObj = (JSONObject)loginResObj.getJSONObject("body").getJSONArray("userList").get(0);
            String realName = userObj.getString("fullName");
            String token = userObj.getString("token");
            accountObj.put("token",token);
            tRecipientInfo.setRealName(realName);
            tRecipientInfo.setAccountJson(accountObj.toJSONString());
            tRecipientInfo.setOnline(1);
            tRecipientInfoService.updateTRecipientInfo(tRecipientInfo);
            return success("登录成功");
        }else if (tRecipientInfo.getChannel().contains("wechat_skd")) {
            String accountJson = tRecipientInfo.getAccountJson();
            JSONObject  accountObj = JSONObject.parseObject(accountJson);
            String ck = accountObj.getString("ck");
            String sid = getParamByUrl(ck, "sid");
            String miniprogram_version = getParamByUrl(ck, "miniprogram_version");
            if(StringUtils.isBlank(miniprogram_version)){
                miniprogram_version ="3.15.9";
            }

//            String account_id = accountObj.getString("account_id");
//            String account_type = accountObj.getString("account_type");
//            String account_type = accountObj.getString("account_type");

            headerMap.put("User-Agent","Mozilla/5.0 (iPhone; CPU iPhone OS 17_7_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 MicroMessenger/8.0.53(0x18003531) NetType/4G Language/zh_CN");
            headerMap.put("Connection","keep-alive");
            headerMap.put("content-type","application/json");
            headerMap.put("Accept-Encoding","gzip,compress,br,deflate");

                //https://payapp.wechatpay.cn/receiptwxmgr/account/list?miniprogram_version=3.15.9&sid=BAFSoGWjZ9j22mkYz7ze55S3uQDlAYgBL4zpQfO_4ofBTw
            String accountUrl = "https://payapp.wechatpay.cn/receiptwxmgr/account/list?miniprogram_version="+miniprogram_version+"&sid="+sid;
            logger.info("获取账号信息链接："+accountUrl);
            HttpResponse accountResponse =  HttpUtils.httpFormGet(accountUrl,headerMap,"","","");
            JSONObject  accountResponseObj  = JSONObject.parseObject(accountResponse.getBody());
            logger.info("获取账号信息返回："+accountResponseObj.toJSONString());
            if(accountResponseObj.getInteger("errcode")!=0){
                logger.info("========修改收款账号为不可用===============");

                tRecipientInfo.setOnline(0);
                tRecipientInfo.setDisabledInfo(accountResponseObj.getString("msg"));
                tRecipientInfoService.updateTRecipientInfo(tRecipientInfo);
                return error("获取账号信息失败："+accountResponseObj.getString("msg"));
            }
            JSONArray account_list = accountResponseObj.getJSONObject("data").getJSONArray("account_list");
            JSONObject wxaccountObj = null;
            for (int i = 0; i < account_list.size(); i++) {
                JSONObject account = account_list.getJSONObject(i);
                if(account.getString("account_type").equals("2")){
                    wxaccountObj = account;
                    break;
                }
            }
            if(wxaccountObj==null){
                return error("获取账号信息失败");
            }

            String account_id = wxaccountObj.getString("account_id");
            String account_type = wxaccountObj.getString("account_type");
            String account_name = wxaccountObj.getString("account_name");
            String  account_status = wxaccountObj.getString("account_status");
            logger.info("获取账号信息：account_id：{}，account_type：{}，account_name：{}，account_status：{}",account_id,account_type,account_name,account_status);
            if(!account_status.equals("ACTIVATED")){
                logger.info("========修改收款账号为不可用===============");
                tRecipientInfo.setOnline(0);
                tRecipientInfo.setDisabledInfo("账号状态异常");
                tRecipientInfoService.updateTRecipientInfo(tRecipientInfo);
                return error("收款账号状态异常");
            }
            accountObj.put("miniprogram_version", miniprogram_version);
            accountObj.put("account_id", account_id);
            accountObj.put("account_type", account_type);
            accountObj.put("sid", sid);
            tRecipientInfo.setAccountJson(accountObj.toJSONString());
            tRecipientInfo.setRealName(account_name);
            tRecipientInfo.setOnline(1);
            tRecipientInfo.setLastOpenTime(new Date());
            tRecipientInfoService.updateTRecipientInfo(tRecipientInfo);
            return success("登录成功");
        }else if (tRecipientInfo.getChannel().contains("dongwo")) {
            String accountJson = tRecipientInfo.getAccountJson();
            JSONObject  accountObj = JSONObject.parseObject(accountJson);
            String token = accountObj.getString("ck");
            JSONObject  reqOrderObj  = new JSONObject();
            headerMap.put("Authorization","Bearer "+token);
            headerMap.put("User-Agent","Mozilla/5.0 (iPhone; CPU iPhone OS 17_7_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 appId=com.daimao.dongwo");
            //获取登录用户信息
            long time = System.currentTimeMillis();
            String version = "2.0.18";
            //获取shopid
            String sign = DongWoPayUtils.getSign(time,"/easyhome-app-application/member/personalInfo",version,reqOrderObj);
            String personalInfoUrl = "https://gateway.jrdaimao.com/easyhome-app-application/member/personalInfo?requestTime="+time+"&dwSign="+sign+"&dwrsv="+version;
            logger.info("personalInfo 请求地址:{}，请求参数：{}",personalInfoUrl,reqOrderObj.toJSONString());
            String personalInfoRes = HttpUtils.sendJsonMessage(personalInfoUrl,headerMap,reqOrderObj.toJSONString());
            JSONObject  personalInfoResObj = JSONObject.parseObject(personalInfoRes);
            logger.info("personalInfo 返回:{}",personalInfoResObj.toJSONString());
            if(personalInfoResObj.getIntValue("code")!=200){
                logger.info("========修改收款账号为不可用===============");
                tRecipientInfo.setOnline(0);
                tRecipientInfo.setDisabledInfo("账号状态异常");
                tRecipientInfoService.updateTRecipientInfo(tRecipientInfo);
                return error("收款账号状态异常");
            }
            String memberId = personalInfoResObj.getJSONObject("data").getString("memberId");

            String merchantId = personalInfoResObj.getJSONObject("data").getString("merchantId");
            String userName = personalInfoResObj.getJSONObject("data").getString("userName");
            String phone = personalInfoResObj.getJSONObject("data").getString("phone");
            accountObj.put("memberId", memberId);
            accountObj.put("merchantId", merchantId);
            accountObj.put("userName", userName);
            accountObj.put("phone", phone);
            tRecipientInfo.setAccountJson(accountObj.toJSONString());
            tRecipientInfo.setRealName(personalInfoResObj.getString("merchantName"));
            tRecipientInfo.setOnline(1);
            tRecipientInfo.setLastOpenTime(new Date());
            tRecipientInfoService.updateTRecipientInfo(tRecipientInfo);
            return success("登录成功");
        }else if (tRecipientInfo.getChannel().contains("alipay_zdt_h5")) {
            String accountJson = tRecipientInfo.getAccountJson();
            JSONObject  accountObj = JSONObject.parseObject(accountJson);
            JSONObject  loginObj  = new JSONObject();
            Base64.Encoder encoder = Base64.getEncoder();

            loginObj.put("ip",encoder.encodeToString(accountObj.getString("password").getBytes()));
            loginObj.put("ia",encoder.encodeToString(tRecipientInfo.getChannelAccount().getBytes()));

            headerMap.put("User-Agent","Mozilla/5.0 (iPhone; CPU iPhone OS 18_1_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 Html5Plus/1.0 (Immersed/47) uni-app");
            //获取登录用户信息
            String loginUrl = "https://mch.zdt.bytedt.cn/api/anon/auth/validate";
            logger.info("loginUrl 请求地址:{}，请求参数：{}",loginUrl,loginObj.toJSONString());
            String personalInfoRes = HttpUtils.sendJsonMessage(loginUrl,headerMap,loginObj.toJSONString());
            JSONObject  personalInfoResObj = JSONObject.parseObject(personalInfoRes);
            logger.info("loginUrl 返回:{}",personalInfoResObj.toJSONString());
            if(personalInfoResObj.getIntValue("code")!=0){
                logger.info("========修改收款账号为不可用===============");
                tRecipientInfo.setOnline(0);
                tRecipientInfo.setDisabledInfo("账号密码错误");
                tRecipientInfoService.updateTRecipientInfo(tRecipientInfo);
                return error("账号密码错误");
            }
            String iToken = personalInfoResObj.getJSONObject("data").getString("iToken");
            accountObj.put("ck", iToken);
            tRecipientInfo.setAccountJson(accountObj.toJSONString());
            tRecipientInfo.setOnline(1);
            tRecipientInfo.setLastOpenTime(new Date());
            tRecipientInfoService.updateTRecipientInfo(tRecipientInfo);
            return success("登录成功");
        }else if (tRecipientInfo.getChannel().contains("lakala_pay")) {

            tRecipientInfo.setOnline(1);
            tRecipientInfo.setLastOpenTime(new Date());
            tRecipientInfoService.updateTRecipientInfo(tRecipientInfo);
            return success("登录成功");
        }
        return toAjax(0);

    }


    @Log(title = "用户收款号状态变更", businessType = BusinessType.UPDATE)
    @RequiresPermissions("business:recipientInfo:edit")
    @PostMapping("/changeOnLineStatus")
    @ResponseBody
    public AjaxResult changeOnLineStatus(TRecipientInfo tUserRecipientInfo) {
        TRecipientInfo newtUserRecipientInfo = tRecipientInfoService.selectTRecipientInfoById(tUserRecipientInfo.getId());
        newtUserRecipientInfo.setOnline(tUserRecipientInfo.getOnline());
        return toAjax(tRecipientInfoService.updateTRecipientInfo(newtUserRecipientInfo));
//        return toAjax(tNginxInfoService.updateTNginxInfo(tNginxInfo));
    }

    @Log(title = "用户收款号状态变更", businessType = BusinessType.UPDATE)
    @RequiresPermissions("business:recipientInfo:edit")
    @PostMapping("/changeChannelDisabledStatus")
    @ResponseBody
    public AjaxResult changeChannelDisabledStatus(TRecipientInfo tUserRecipientInfo) {
        TRecipientInfo newtUserRecipientInfo = tRecipientInfoService.selectTRecipientInfoById(tUserRecipientInfo.getId());
        newtUserRecipientInfo.setChannelDisabled(tUserRecipientInfo.getChannelDisabled());
        return toAjax(tRecipientInfoService.updateTRecipientInfo(newtUserRecipientInfo));
//        return toAjax(tNginxInfoService.updateTNginxInfo(tNginxInfo));
    }


    @Log(title = "用户收款号状态变更", businessType = BusinessType.UPDATE)
    @RequiresPermissions("business:recipientInfo:edit")
    @PostMapping("/changeAvailableStatus")
    @ResponseBody
    public AjaxResult changeAvailableStatus(TRecipientInfo tUserRecipientInfo) {
        TRecipientInfo newtUserRecipientInfo = tRecipientInfoService.selectTRecipientInfoById(tUserRecipientInfo.getId());
        newtUserRecipientInfo.setAvailable(tUserRecipientInfo.getAvailable());
        return toAjax(tRecipientInfoService.updateTRecipientInfo(newtUserRecipientInfo));
//        return toAjax(tNginxInfoService.updateTNginxInfo(tNginxInfo));
    }

    @GetMapping("/getGroupName")
    @ResponseBody
    public AjaxResult getGroupName()
    {
        AjaxResult ajax = new AjaxResult();
        TRecipientInfo  tRecipientInfo = new TRecipientInfo();
//        tRecipientInfo.setUserId(ShiroUtils.getUserId());
        List<TRecipientInfo> list = tRecipientInfoService.selectTRecipientGroupNameList(tRecipientInfo);
        String[] array = new String[list.size()];
        for (int i = 0; i < list.size(); i++) {
            array[i] = list.get(i).getGroupName();
        }
        ajax.put("value", array);
        return ajax;
    }

    @PostMapping("/checkCK/{id}")
    @ResponseBody
    public AjaxResult checkCK(@PathVariable("id") Long id)
    {
        TRecipientInfo tRecipientInfo = tRecipientInfoService.selectTRecipientInfoById(id);
        long userId = ShiroUtils.getUserId();
        TPayChannel payChannelParam = new TPayChannel();
        payChannelParam.setChannel(tRecipientInfo.getChannel());
        TPayChannel orderChannel = payChannelService.selectTPayChannelList(payChannelParam).get(0);
        if(!"ck".equals(orderChannel.getLoginType())){
            return success("该通道无需检测CK");
        }
        HashMap<String, String> headerMap = new HashMap();
        if (tRecipientInfo.getChannel().contains("wechat_skd")) {
            String accountJson = tRecipientInfo.getAccountJson();
            JSONObject  accountObj = JSONObject.parseObject(accountJson);
            String ck = accountObj.getString("ck");
            String sid = getParamByUrl(ck, "sid");
            String miniprogram_version = getParamByUrl(ck, "miniprogram_version");
            if(StringUtils.isBlank(miniprogram_version)){
                miniprogram_version ="3.15.9";
            }
            //String account_id = getParamByUrl(ck, "account_id");
            //String account_type = getParamByUrl(ck, "account_type");

            headerMap.put("User-Agent","Mozilla/5.0 (iPhone; CPU iPhone OS 17_7_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 MicroMessenger/8.0.53(0x18003531) NetType/4G Language/zh_CN");
            headerMap.put("Connection","keep-alive");
            headerMap.put("content-type","application/json");
            headerMap.put("Accept-Encoding","gzip,compress,br,deflate");

            //https://payapp.wechatpay.cn/receiptwxmgr/account/list?miniprogram_version=3.15.9&sid=BAFSoGWjZ9j22mkYz7ze55S3uQDlAYgBL4zpQfO_4ofBTw
            String accountUrl = "https://payapp.wechatpay.cn/receiptwxmgr/account/list?miniprogram_version="+miniprogram_version+"&sid="+sid;
            HttpResponse accountResponse =  HttpUtils.httpFormGet(accountUrl,headerMap,"","","");
            JSONObject  accountResponseObj  = JSONObject.parseObject(accountResponse.getBody());
            logger.info("返回：{}",accountResponseObj.toJSONString());
            if(accountResponseObj.getInteger("errcode")!=0){
                logger.info("========修改收款账号为不可用===============");

                tRecipientInfo.setOnline(0);
                tRecipientInfo.setDisabledInfo(accountResponseObj.getString("msg"));
                tRecipientInfoService.updateTRecipientInfo(tRecipientInfo);
                return error("检测CK失败："+accountResponseObj.getString("msg"));
            }
            JSONArray account_list = accountResponseObj.getJSONObject("data").getJSONArray("account_list");
            JSONObject wxaccountObj = null;
            for (int i = 0; i < account_list.size(); i++) {
                JSONObject account = account_list.getJSONObject(i);
                if(account.getString("account_type").equals("2")){
                    wxaccountObj = account;
                    break;
                }
            }
            if(wxaccountObj==null){
                return error("获取账号信息失败");
            }

            String account_id = wxaccountObj.getString("account_id");
            String account_type = wxaccountObj.getString("account_type");
            String account_name = wxaccountObj.getString("account_name");
            String  account_status = wxaccountObj.getString("account_status");
            if(!account_status.equals("ACTIVATED")){
                logger.info("========修改收款账号为不可用===============");
                tRecipientInfo.setOnline(0);
                tRecipientInfo.setDisabledInfo("账号状态异常");
                tRecipientInfoService.updateTRecipientInfo(tRecipientInfo);
                return error("收款账号状态异常");
            }
            accountObj.put("miniprogram_version", miniprogram_version);
            accountObj.put("account_id", account_id);
            accountObj.put("account_type", account_type);
            accountObj.put("sid", sid);
            tRecipientInfo.setAccountJson(accountObj.toJSONString());
            tRecipientInfo.setRealName(account_name);
            tRecipientInfo.setOnline(1);
            tRecipientInfoService.updateTRecipientInfo(tRecipientInfo);
            return success("检测CK正常");
        }else if (tRecipientInfo.getChannel().contains("dongwo")) {
            String accountJson = tRecipientInfo.getAccountJson();
            JSONObject  accountObj = JSONObject.parseObject(accountJson);
            String token = accountObj.getString("ck");
            JSONObject  reqOrderObj  = new JSONObject();
            headerMap.put("Authorization","Bearer "+token);
            headerMap.put("User-Agent","Mozilla/5.0 (iPhone; CPU iPhone OS 17_7_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 appId=com.daimao.dongwo");
            //获取登录用户信息
            long time = System.currentTimeMillis();
            String version = "2.0.18";
            //获取shopid
            String sign = DongWoPayUtils.getSign(time,"/easyhome-app-application/member/personalInfo",version,reqOrderObj);
            String personalInfoUrl = "https://gateway.jrdaimao.com/easyhome-app-application/member/personalInfo?requestTime="+time+"&dwSign="+sign+"&dwrsv="+version;
            logger.info("personalInfo 请求地址:{}，请求参数：{}",personalInfoUrl,reqOrderObj.toJSONString());
            String personalInfoRes = HttpUtils.sendJsonMessage(personalInfoUrl,headerMap,reqOrderObj.toJSONString());
            JSONObject  personalInfoResObj = JSONObject.parseObject(personalInfoRes);
            logger.info("personalInfo 返回:{}",personalInfoResObj.toJSONString());
            if(personalInfoResObj.getIntValue("code")!=200){
                logger.info("========修改收款账号为不可用===============");
                tRecipientInfo.setOnline(0);
                tRecipientInfo.setDisabledInfo("账号状态异常");
                tRecipientInfoService.updateTRecipientInfo(tRecipientInfo);
                return error("收款账号状态异常");
            }
            String memberId = personalInfoResObj.getJSONObject("data").getString("memberId");

            String merchantId = personalInfoResObj.getJSONObject("data").getString("merchantId");
            String userName = personalInfoResObj.getJSONObject("data").getString("userName");
            String phone = personalInfoResObj.getJSONObject("data").getString("phone");
            accountObj.put("memberId", memberId);
            accountObj.put("merchantId", merchantId);
            accountObj.put("userName", userName);
            accountObj.put("phone", phone);
            tRecipientInfo.setAccountJson(accountObj.toJSONString());
            tRecipientInfo.setRealName(personalInfoResObj.getString("merchantName"));
            tRecipientInfo.setOnline(1);
            tRecipientInfo.setLastOpenTime(new Date());
            tRecipientInfoService.updateTRecipientInfo(tRecipientInfo);
            return success("检测CK正常");
        }
        return toAjax(0);
    }

    @Log(title = "测试用户收款号", businessType = BusinessType.UPDATE)
    @PostMapping("/testPay")
    @ResponseBody
    public AjaxResult testPay(TRecipientInfo tUserRecipientInfo) throws Exception {
        return chargeServiceImpl.testPay(tUserRecipientInfo);
    }


    //serviceRecip

    @Log(title = "分配子账户", businessType = BusinessType.UPDATE)
    @PostMapping("/serviceRecip")
    @ResponseBody
    public AjaxResult serviceRecip(Long userId, Long[] ids) throws Exception {
        tRecipientInfoService.serviceRecip(userId,ids);
        return success();
    }

    /**
     * 查询收款账号列表
     */
    @RequiresPermissions("business:recipientInfo:list")
    @PostMapping("/serviceRecipList")
    @ResponseBody
    public TableDataInfo serviceRecipList(TRecipientInfo tRecipientInfo)
    {
        tRecipientInfo.setUserId(null);
        startPage();
        List<TRecipientInfo> list = tRecipientInfoService.selectTRecipientInfoList(tRecipientInfo);
        return getDataTable(list);
    }


}
